package com.ruoyi.client.service.impl;

import com.ruoyi.client.mapper.NovelDetailMapper;
import com.ruoyi.client.mapper.NovelLikesMapper;
import com.ruoyi.client.pojo.vo.ChapterVo;
import com.ruoyi.client.pojo.vo.NovelVo;
import com.ruoyi.client.service.NovelDetailService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class NovelDetailServiceImpl implements NovelDetailService {

    @Resource
    NovelDetailMapper novelDetailMapper;
    
    @Resource
    NovelLikesMapper novelLikesMapper;

    @Override
    public NovelVo listDetailId(long novel_id) {
        return novelDetailMapper.listDetailId(novel_id);
    }

    @Override
    public ChapterVo chapterDetailId(long chapter_id) {
        return novelDetailMapper.chapterDetailId(chapter_id);
    }
    
    @Override
    public boolean incrementViewCount(Long novelId) {
        try {
            int result = novelDetailMapper.incrementViewCount(novelId);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean checkUserLike(Long userId, Long novelId) {
        int count = novelLikesMapper.checkUserLike(userId, novelId);
        return count > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleLike(Long userId, Long novelId) {
        // 检查用户是否已点赞
        boolean isLiked = checkUserLike(userId, novelId);
        
        if (isLiked) {
            // 已点赞，执行取消点赞
            novelLikesMapper.deleteLike(userId, novelId);
            novelDetailMapper.decrementLikeCount(novelId);
            return false;
        } else {
            // 未点赞，执行点赞
            novelLikesMapper.insertLike(userId, novelId);
            novelDetailMapper.incrementLikeCount(novelId);
            return true;
        }
    }
}